Popular Searches
Popular Course Categories
Popular Courses

Select Dropdown

Dropdowns & Advanced Elements

Select Dropdown in Selenium WebDriver

A Select Dropdown is a common form control used on websites to allow users to choose one or more options from a predefined list. Examples include selecting a country, state, city, department, gender, category, month, year, payment method, or job role.

In Selenium WebDriver with Java, standard HTML dropdowns created using the <select> element can be handled conveniently using Selenium's Select class. The Select class provides methods such as selectByVisibleText(), selectByValue(), selectByIndex(), getOptions(), and methods for handling multiple selections.

Selenium Training: Selenium Training Course

Register for Course Demo: Register for Selenium Course Demo


1. What is a Select Dropdown?

A select dropdown is an HTML form element that presents a list of predefined options. The standard HTML structure uses the <select> element as the container and one or more <option> elements as its choices.

<select id="country">

    <option value="india">India</option>

    <option value="usa">United States</option>

    <option value="uk">United Kingdom</option>

    <option value="canada">Canada</option>

</select>

In this example, country is the select element and each country is an option.


2. Why Dropdown Handling is Important in Selenium

Dropdowns are frequently used in real-world web applications. Automated tests often need to select a particular value and then verify that the correct value has been selected.

  • Country selection
  • State selection
  • City selection
  • Product category selection
  • Department selection
  • Month and year selection
  • Payment method selection
  • Language selection
  • Employment type selection
  • Registration form selections


3. HTML Structure of a Select Dropdown

<label for="department">Department</label>

 

<select id="department" name="department">

    <option value="it">IT</option>

    <option value="hr">Human Resources</option>

    <option value="finance">Finance</option>

    <option value="sales">Sales</option>

</select>

The important elements are:

Element/AttributePurpose
<select>Creates the dropdown
<option>Represents an option inside the dropdown
idProvides a unique identifier
nameIdentifies the form field
valueProvides the option's submitted value
multipleAllows multiple options to be selected


4. Selenium Select Class

Selenium provides the org.openqa.selenium.support.ui.Select class for interacting with standard HTML <select> elements. The class wraps a WebElement representing a select element and provides specialized dropdown operations.

Import the Select class using:

import org.openqa.selenium.support.ui.Select;


5. Basic Select Class Syntax

WebElement dropdown = driver.findElement(By.id("country"));

Select select = new Select(dropdown);

After creating the Select object, selection methods can be called on it.


6. Complete Basic Example

WebElement countryDropdown =

        driver.findElement(By.id("country"));

 

Select country =

        new Select(countryDropdown);

 

country.selectByVisibleText("India");


7. Select by Visible Text

selectByVisibleText() selects an option according to the text displayed to the user.

WebElement dropdown =

        driver.findElement(By.id("country"));

 

Select select =

        new Select(dropdown);

 

select.selectByVisibleText("India");

For example:

<select id="country">

    <option value="in">India</option>

    <option value="us">United States</option>

</select>

The following selects India:

select.selectByVisibleText("India");


8. Advantages of selectByVisibleText()

  • Easy to read.
  • Easy to understand.
  • Matches what the user sees.
  • Useful when option text is stable.
  • Makes test cases more readable.

For most straightforward dropdown scenarios, visible text is often a clear way to express the intended selection.


9. Select by Value

selectByValue() selects an option by matching its HTML value attribute.

<select id="country">

    <option value="in">India</option>

    <option value="us">United States</option>

    <option value="uk">United Kingdom</option>

</select>

Java Selenium:

Select select =

        new Select(driver.findElement(By.id("country")));

 

select.selectByValue("in");


10. When to Use selectByValue()

Use selectByValue() when the option's value attribute is stable and known.

select.selectByValue("india");

This method is useful when visible text changes but the underlying value remains stable.


11. Select by Index

selectByIndex() selects an option using its index.

Select select =

        new Select(driver.findElement(By.id("country")));

 

select.selectByIndex(2);

When using index-based selection, be careful if the application's option ordering can change.


12. Example of selectByIndex()

<select id="city">

    <option value="delhi">Delhi</option>

    <option value="mumbai">Mumbai</option>

    <option value="pune">Pune</option>

    <option value="bangalore">Bangalore</option>

</select>

Select city =

        new Select(driver.findElement(By.id("city")));

 

city.selectByIndex(2);

Index-based selection should be used carefully because changes to option ordering can make the test select a different option.


13. Three Main Selection Methods

MethodSelection BasisExample
selectByVisibleText()Displayed option textIndia
selectByValue()HTML value attributein
selectByIndex()Option index2


14. Difference Between the Three Selection Methods

FeatureVisible TextValueIndex
Uses displayed textYesNoNo
Uses value attributeNoYesNo
Uses indexNoNoYes
Easy to readVery easyEasyModerate
Depends on option orderNoNoYes
Useful for dynamic option textSometimesOftenSometimes


15. How Select Dropdown Handling Works

Locate <select> element

        |

        v

Create Select object

        |

        v

Choose selection strategy

        |

        +----------------------+

        |          |           |

        v          v           v

Visible Text    Value       Index

        |          |           |

        +----------+-----------+

                   |

                   v

            Option Selected

                   |

                   v

            Verify Selection


16. Complete Dropdown Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

 

public class DropdownExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com");

 

            WebElement countryDropdown =

                    driver.findElement(By.id("country"));

 

            Select country =

                    new Select(countryDropdown);

 

            country.selectByVisibleText("India");

 

        } finally {

            driver.quit();

        }

    }

}


17. Getting All Dropdown Options

The getOptions() method returns all options belonging to the select element.

Select select =

        new Select(driver.findElement(By.id("country")));

 

List<WebElement> options =

        select.getOptions();

Required import:

import java.util.List;


18. Printing All Dropdown Options

List<WebElement> options = select.getOptions();

 

for (WebElement option : options) {

    System.out.println(option.getText());

}

This is useful for debugging and validating that expected options are present.


19. Complete Example to Print Options

WebElement dropdown =

        driver.findElement(By.id("country"));

 

Select select =

        new Select(dropdown);

 

List<WebElement> options =

        select.getOptions();

 

for (WebElement option : options) {

    System.out.println(

            "Option: " + option.getText()

    );

}


20. Getting the First Selected Option

The getFirstSelectedOption() method returns the first selected option. For a normal single-select dropdown, this represents the currently selected option.

WebElement selected =

        select.getFirstSelectedOption();

 

System.out.println(

        selected.getText()

);


21. Verifying the Selected Option

select.selectByVisibleText("India");

 

String selectedText =

        select.getFirstSelectedOption().getText();

 

System.out.println(

        "Selected: " + selectedText

);

TestNG assertion:

Assert.assertEquals(

        selectedText,

        "India"

);


22. Getting All Selected Options

The getAllSelectedOptions() method returns all currently selected options. For a normal single-select dropdown, this list generally contains one selected option; for a multiple-select dropdown, it can contain multiple options.

List<WebElement> selectedOptions =

        select.getAllSelectedOptions();

 

for (WebElement option : selectedOptions) {

    System.out.println(option.getText());

}


23. Checking Whether Dropdown Supports Multiple Selection

The isMultiple() method checks whether the select element supports selecting multiple options.

if (select.isMultiple()) {

    System.out.println(

            "Multiple selection is supported"

    );

} else {

    System.out.println(

            "Single selection only"

    );

}


24. Single Select Dropdown

A standard single-select dropdown allows one option to be selected at a time.

<select id="department">

    <option value="it">IT</option>

    <option value="hr">HR</option>

    <option value="finance">Finance</option>

</select>

Example:

Select department =

        new Select(

                driver.findElement(

                        By.id("department")

                )

        );

 

department.selectByVisibleText("IT");


25. Multiple Select Dropdown

A multiple-select dropdown uses the multiple attribute and allows more than one option to be selected.

<select id="skills" multiple>

    <option value="java">Java</option>

    <option value="selenium">Selenium</option>

    <option value="sql">SQL</option>

    <option value="python">Python</option>

</select>


26. Selecting Multiple Options

The Select methods can be called repeatedly for a multiple-select dropdown.

Select skills =

        new Select(

                driver.findElement(By.id("skills"))

        );

 

skills.selectByVisibleText("Java");

skills.selectByVisibleText("Selenium");

skills.selectByVisibleText("SQL");


27. Deselect by Visible Text

For multiple-select dropdowns, deselectByVisibleText() removes a selected option based on its displayed text.

skills.deselectByVisibleText("SQL");


28. Deselect by Value

skills.deselectByValue("selenium");

This removes the selected option whose value attribute matches the supplied value.


29. Deselect by Index

skills.deselectByIndex(2);

This is applicable to multiple-select dropdowns.


30. Deselect All

The deselectAll() method clears all selected options. It is intended for multiple-select elements.

skills.deselectAll();


31. Selecting and Deselecting Multiple Options

Select skills =

        new Select(

                driver.findElement(By.id("skills"))

        );

 

skills.selectByVisibleText("Java");

skills.selectByVisibleText("Selenium");

skills.selectByVisibleText("SQL");

 

skills.deselectByVisibleText("SQL");


32. Complete Multiple Select Example

WebElement skillsDropdown =

        driver.findElement(By.id("skills"));

 

Select skills =

        new Select(skillsDropdown);

 

skills.selectByVisibleText("Java");

skills.selectByVisibleText("Selenium");

skills.selectByVisibleText("SQL");

 

List<WebElement> selected =

        skills.getAllSelectedOptions();

 

for (WebElement option : selected) {

    System.out.println(

            "Selected: " + option.getText()

    );

}


33. Select Class Works Only with <select>

An important point is that Selenium's Java Select class is designed for actual HTML <select> elements. It should not be used with custom dropdowns implemented using elements such as <div>, <li>, buttons, or other custom components.


34. Standard Dropdown vs Custom Dropdown

Standard DropdownCustom Dropdown
Uses <select>Often uses <div>, <li>, buttons, etc.
Contains <option>May contain custom elements
Can use Select classSelect class does not apply
selectByVisibleText() availableMust interact with elements directly
selectByValue() availableUsually handled with locators/clicks


35. Example of a Custom Dropdown

<div class="dropdown">

    <button>Select Country</button>

 

    <div class="options">

        <div>India</div>

        <div>United States</div>

        <div>United Kingdom</div>

    </div>

</div>

This is not a standard <select> element, so the Select class should not be used.


36. Handling a Custom Dropdown

For a custom dropdown, interact with the actual elements displayed by the application.

driver.findElement(

        By.cssSelector(".dropdown button")

).click();

 

driver.findElement(

        By.xpath("//div[text()='India']")

).click();

The exact locator depends on the application's HTML structure.


37. Why Select Class May Throw an Exception

The Select constructor expects the supplied WebElement to represent a SELECT element. If the element is not a select element, Selenium can throw an UnexpectedTagNameException.

WebElement element =

        driver.findElement(By.id("country"));

 

Select select = new Select(element);

If the element is actually a div-based custom dropdown, the Select object should not be created for it.


38. Handling Dropdown Using ID Locator

Select country =

        new Select(

                driver.findElement(

                        By.id("country")

                )

        );

 

country.selectByVisibleText("India");


39. Handling Dropdown Using Name Locator

Select country =

        new Select(

                driver.findElement(

                        By.name("country")

                )

        );

 

country.selectByVisibleText("India");


40. Handling Dropdown Using CSS Selector

Select country =

        new Select(

                driver.findElement(

                        By.cssSelector("#country")

                )

        );

 

country.selectByVisibleText("India");


41. Handling Dropdown Using XPath

Select country =

        new Select(

                driver.findElement(

                        By.xpath("//select[@id='country']")

                )

        );

 

country.selectByVisibleText("India");


42. Handling Dropdown with WebElement Variable

WebElement countryElement =

        driver.findElement(

                By.id("country")

        );

 

Select country =

        new Select(countryElement);

 

country.selectByVisibleText("India");

This approach is often easier to debug because the WebElement and Select objects are clearly separated.


43. Verifying All Expected Options

Test automation may need to verify that required options are available.

List<WebElement> options =

        country.getOptions();

 

for (WebElement option : options) {

    String text = option.getText();

    System.out.println(text);

}


44. Checking Whether an Option Exists

boolean optionFound = false;

 

for (WebElement option : country.getOptions()) {

    if (option.getText().equals("India")) {

        optionFound = true;

        break;

    }

}

 

System.out.println(

        "India available: " + optionFound

);


45. Selecting an Option Dynamically

Sometimes the option to select is stored in a variable.

String countryName = "India";

 

Select country =

        new Select(

                driver.findElement(

                        By.id("country")

                )

        );

 

country.selectByVisibleText(countryName);

This makes the same automation method reusable for different test data.


46. Data-Driven Dropdown Selection

String[] countries = {

        "India",

        "United States",

        "United Kingdom"

};

 

for (String countryName : countries) {

 

    Select country =

            new Select(

                    driver.findElement(

                            By.id("country")

                    )

            );

 

    country.selectByVisibleText(countryName);

 

    System.out.println(

            "Selected: " + countryName

    );

}


47. Dropdown with TestNG Assertion

WebElement countryElement =

        driver.findElement(By.id("country"));

 

Select country =

        new Select(countryElement);

 

country.selectByVisibleText("India");

 

String selected =

        country.getFirstSelectedOption()

               .getText();

 

Assert.assertEquals(

        selected,

        "India"

);


48. Required Imports for Dropdown Testing

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

 

import org.testng.Assert;


49. Complete TestNG Dropdown Test

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class DropdownTest {

 

    @Test

    public void selectCountry() {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com");

 

            WebElement countryElement =

                    driver.findElement(

                            By.id("country")

                    );

 

            Select country =

                    new Select(countryElement);

 

            country.selectByVisibleText("India");

 

            String selected =

                    country

                    .getFirstSelectedOption()

                    .getText();

 

            Assert.assertEquals(

                    selected,

                    "India"

            );

 

        } finally {

            driver.quit();

        }

    }

}


50. Dropdown Selection Flow

Launch Browser

      |

      v

Open Web Page

      |

      v

Locate <select> Element

      |

      v

Create Select Object

      |

      v

Choose Selection Method

      |

      +-------------------------+

      |            |            |

      v            v            v

Visible Text    Value        Index

      |            |            |

      +------------+------------+

                   |

                   v

             Select Option

                   |

                   v

             Verify Selection

                   |

                   v

              Continue Test


51. Dropdown Testing Scenarios

Important test scenarios for dropdowns include:

  • Verify dropdown is displayed.
  • Verify dropdown is enabled.
  • Verify expected options are present.
  • Select an option using visible text.
  • Select an option using value.
  • Select an option using index.
  • Verify the selected option.
  • Verify default selection.
  • Verify multiple-selection behavior where supported.
  • Verify disabled options.
  • Verify that invalid selections are not accepted.
  • Verify dependent dropdown behavior.


52. Testing Default Selected Option

A dropdown may have a default option selected when the page loads.

WebElement dropdown =

        driver.findElement(By.id("country"));

 

Select select =

        new Select(dropdown);

 

String defaultOption =

        select.getFirstSelectedOption()

              .getText();

 

System.out.println(

        "Default: " + defaultOption

);


53. Testing Disabled Dropdown

A dropdown can be disabled using the HTML disabled attribute.

<select id="country" disabled>

    <option value="in">India</option>

    <option value="us">United States</option>

</select>

Before interacting with a disabled dropdown, verify its state and ensure the test case reflects the expected application behavior.


54. Testing Disabled Options

An individual option can also be disabled.

<select id="country">

    <option value="in">India</option>

    <option value="us" disabled>United States</option>

</select>

A disabled option should not be treated as a valid selectable option in the test.


55. Dependent Dropdowns

Many applications use dependent dropdowns. For example, selecting a country may dynamically populate a state dropdown.

Country

   |

   v

Select India

   |

   v

State Dropdown Updated

   |

   v

Select Maharashtra

   |

   v

City Dropdown Updated

   |

   v

Select Mumbai

In such cases, synchronization may be required between each selection and the appearance of the new options.


56. Example of Dependent Dropdown

Select country =

        new Select(

                driver.findElement(

                        By.id("country")

                )

        );

 

country.selectByVisibleText("India");

 

// Wait for state options to become available

 

Select state =

        new Select(

                driver.findElement(

                        By.id("state")

                )

        );

 

state.selectByVisibleText("Maharashtra");


57. Waiting for Dynamic Dropdown Options

If a dropdown is populated asynchronously after another selection, use an appropriate explicit wait rather than assuming the options are immediately available.

WebDriverWait wait =

        new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

        );

 

wait.until(

        d -> d.findElements(

                By.cssSelector("#state option")

        ).size() > 1

);

Required imports:

import java.time.Duration;

import org.openqa.selenium.support.ui.WebDriverWait;


58. Dynamic Dropdown Example

country.selectByVisibleText("India");

 

WebDriverWait wait =

        new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

        );

 

wait.until(

        d -> d.findElements(

                By.cssSelector("#state option")

        ).size() > 1

);

 

Select state =

        new Select(

                driver.findElement(

                        By.id("state")

                )

        );

 

state.selectByVisibleText("Maharashtra");


59. Common Dropdown Exceptions

ExceptionPossible Cause
UnexpectedTagNameExceptionElement is not a <select> element
NoSuchElementExceptionRequested option does not exist
StaleElementReferenceExceptionDropdown or option was refreshed/replaced
ElementNotInteractableExceptionElement cannot currently be interacted with
TimeoutExceptionDynamic dropdown did not become ready within the wait period


60. UnexpectedTagNameException

This exception commonly occurs when the Select class is used with a non-select element.

WebElement element =

        driver.findElement(

                By.id("customDropdown")

        );

 

Select select =

        new Select(element);

If customDropdown is a div, button, or another element instead of a select element, the Select class is inappropriate.


61. NoSuchElementException in Dropdown

This can occur when the requested option cannot be found.

select.selectByVisibleText("Australia");

If the dropdown does not contain an option matching the requested text, the operation fails.


62. Handling Dropdowns with Page Object Model

Dropdown interactions can be encapsulated inside page classes.

public class RegistrationPage {

 

    private WebDriver driver;

 

    private By country =

            By.id("country");

 

    public RegistrationPage(

            WebDriver driver) {

 

        this.driver = driver;

    }

 

    public void selectCountry(

            String countryName) {

 

        Select select =

                new Select(

                        driver.findElement(country)

                );

 

        select.selectByVisibleText(

                countryName

        );

    }

 

    public String getSelectedCountry() {

 

        Select select =

                new Select(

                        driver.findElement(country)

                );

 

        return select

                .getFirstSelectedOption()

                .getText();

    }

}


63. Using the Page Object

RegistrationPage page =

        new RegistrationPage(driver);

 

page.selectCountry("India");

 

Assert.assertEquals(

        page.getSelectedCountry(),

        "India"

);


64. Reusable Dropdown Utility

A framework can provide a reusable utility method for selecting an option by visible text.

public static void selectByText(

        WebDriver driver,

        By locator,

        String text) {

 

    WebElement element =

            driver.findElement(locator);

 

    Select select =

            new Select(element);

 

    select.selectByVisibleText(text);

}

Usage:

DropdownUtils.selectByText(

        driver,

        By.id("country"),

        "India"

);


65. Utility Method for Selecting by Value

public static void selectByValue(

        WebDriver driver,

        By locator,

        String value) {

 

    Select select =

            new Select(

                    driver.findElement(locator)

            );

 

    select.selectByValue(value);

}


66. Utility Method for Selecting by Index

public static void selectByIndex(

        WebDriver driver,

        By locator,

        int index) {

 

    Select select =

            new Select(

                    driver.findElement(locator)

            );

 

    select.selectByIndex(index);

}


67. Best Practice: Prefer Meaningful Selection

Choose a selection strategy according to the application's HTML and test requirement.

  • Use selectByVisibleText() when the displayed text is stable and meaningful.
  • Use selectByValue() when the value attribute is stable and appropriate.
  • Use selectByIndex() only when index-based selection is intentional and stable.


68. Best Practice: Do Not Use Select for Custom Dropdowns

Always inspect the HTML before using the Select class.

<select>       --> Use Select class

<option>       --> Option inside Select

 

<div>          --> Handle directly

<button>       --> Handle directly

<li>           --> Handle directly

The Select class is intended for HTML select/option controls.


69. Best Practice: Avoid Hard-Coded Indexes When Possible

This code may become fragile if the order of options changes:

select.selectByIndex(3);

If the test requirement is actually to select a named option, prefer:

select.selectByVisibleText("India");


70. Best Practice: Verify the Selection

select.selectByVisibleText("India");

 

String selected =

        select.getFirstSelectedOption()

              .getText();

 

Assert.assertEquals(

        selected,

        "India"

);

Verification ensures that the intended selection was actually applied.


71. Best Practice: Use Explicit Waits for Dynamic Dropdowns

For dropdowns whose options are populated after an AJAX or JavaScript operation, wait for the expected condition before selecting.

WebDriverWait wait =

        new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

        );

 

wait.until(

        d -> d.findElements(

                By.cssSelector(

                        "#state option"

                )

        ).size() > 1

);


72. Best Practice: Keep Dropdown Logic Reusable

In a larger Selenium framework, repeated dropdown operations should be placed into reusable utilities or Page Object methods.

selectByText(driver, By.id("country"), "India");

selectByText(driver, By.id("state"), "Maharashtra");

selectByText(driver, By.id("city"), "Mumbai");

This reduces duplicate code and makes test cases easier to maintain.


73. Common Mistakes in Select Dropdown Handling

  • Using Select on a custom dropdown.
  • Forgetting to import org.openqa.selenium.support.ui.Select.
  • Using incorrect option text.
  • Using the wrong value attribute.
  • Assuming an index will always remain unchanged.
  • Trying to deselect an option from a single-select dropdown.
  • Trying to select a disabled option.
  • Not waiting for dynamically loaded options.
  • Not verifying the selected option.
  • Using an incorrect locator for the select element.


74. Incorrect vs Correct Dropdown Handling

Incorrect/FragileBetter Approach
Use Select on a div dropdownInteract with the custom dropdown elements
Always use indexUse visible text or value when appropriate
Select immediately after AJAX updateWait for expected options
Do not verify selectionUse getFirstSelectedOption()
Use random locatorUse stable ID/name/CSS/XPath
Ignore disabled optionsVerify enabled/disabled state when required


75. Practical Project: Registration Form

Scenario: Automate a registration form containing country, state, city, department, and skills dropdowns.

Test Steps

  1. Launch the browser.
  2. Open the registration page.
  3. Locate the country dropdown.
  4. Select India.
  5. Wait for the state dropdown to update.
  6. Select Maharashtra.
  7. Wait for the city dropdown to update.
  8. Select Mumbai.
  9. Select a department.
  10. Select multiple skills if the field supports multiple selections.
  11. Verify the selected values.
  12. Submit the form.
  13. Verify the successful registration message.


76. Registration Form Flow

Open Registration Page

        |

        v

Select Country

        |

        v

Wait for States

        |

        v

Select State

        |

        v

Wait for Cities

        |

        v

Select City

        |

        v

Select Department

        |

        v

Select Skills

        |

        v

Verify Selections

        |

        v

Submit Form

        |

        v

Verify Success


77. Practical Project Code

WebDriver driver = new ChromeDriver();

 

try {

 

    driver.manage().window().maximize();

 

    driver.get("https://example.com/registration");

 

    Select country =

            new Select(

                    driver.findElement(

                            By.id("country")

                    )

            );

 

    country.selectByVisibleText("India");

 

    WebDriverWait wait =

            new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

            );

 

    wait.until(

            d -> d.findElements(

                    By.cssSelector(

                            "#state option"

                    )

            ).size() > 1

    );

 

    Select state =

            new Select(

                    driver.findElement(

                            By.id("state")

                    )

            );

 

    state.selectByVisibleText("Maharashtra");

 

    wait.until(

            d -> d.findElements(

                    By.cssSelector(

                            "#city option"

                    )

            ).size() > 1

    );

 

    Select city =

            new Select(

                    driver.findElement(

                            By.id("city")

                    )

            );

 

    city.selectByVisibleText("Mumbai");

 

    Select department =

            new Select(

                    driver.findElement(

                            By.id("department")

                    )

            );

 

    department.selectByVisibleText("IT");

 

} finally {

 

    driver.quit();

}


78. Dropdown Automation Checklist

  • ☐ Inspect the dropdown HTML.
  • ☐ Confirm whether it is a real <select> element.
  • ☐ Identify the dropdown with a stable locator.
  • ☐ Create a Select object.
  • ☐ Choose visible text, value, or index.
  • ☐ Verify the selected option.
  • ☐ Handle multiple selection if applicable.
  • ☐ Handle dynamic options with appropriate waits.
  • ☐ Test disabled options when relevant.
  • ☐ Use custom interaction for non-select dropdowns.
  • ☐ Keep reusable dropdown logic in utilities/Page Objects.


79. Select Dropdown Cheat Sheet

// Locate dropdown

WebElement element =

        driver.findElement(By.id("country"));

 

// Create Select object

Select select =

        new Select(element);

 

// Select by text

select.selectByVisibleText("India");

 

// Select by value

select.selectByValue("in");

 

// Select by index

select.selectByIndex(1);

 

// Get all options

List<WebElement> options =

        select.getOptions();

 

// Get selected option

WebElement selected =

        select.getFirstSelectedOption();

 

// Get all selected options

List<WebElement> selectedOptions =

        select.getAllSelectedOptions();

 

// Check multiple selection

boolean multiple =

        select.isMultiple();

 

// Deselect by text

select.deselectByVisibleText("India");

 

// Deselect by value

select.deselectByValue("in");

 

// Deselect by index

select.deselectByIndex(1);

 

// Deselect all

select.deselectAll();


80. Interview Question: What is the Select Class in Selenium?

Answer: The Select class is a Selenium support class used to interact with standard HTML <select> dropdown elements. It provides methods for selecting, deselecting, retrieving options, and checking multiple-selection support.


81. Interview Question: How do you select an option by visible text?

Answer:

Select select =

        new Select(

                driver.findElement(

                        By.id("country")

                )

        );

 

select.selectByVisibleText("India");


82. Interview Question: How do you select an option by value?

Answer:

select.selectByValue("in");


83. Interview Question: How do you select an option by index?

Answer:

select.selectByIndex(2);


84. Interview Question: Can Select handle a div-based dropdown?

Answer: No. Selenium's Select class is designed for HTML <select> elements. A custom dropdown implemented using elements such as div, li, or buttons must be handled by interacting with those elements directly.


85. Interview Question: How do you get all options from a dropdown?

Answer: Use getOptions().

List<WebElement> options =

        select.getOptions();


86. Interview Question: How do you get the selected option?

Answer: Use getFirstSelectedOption().

WebElement selected =

        select.getFirstSelectedOption();


87. Interview Question: How do you check whether a dropdown supports multiple selections?

Answer: Use isMultiple().

boolean multiple =

        select.isMultiple();


88. Interview Question: Can we deselect an option from a single-select dropdown?

Answer: Deselect operations are intended for multiple-select dropdowns. A normal single-select dropdown does not support clearing an individual selection through the multiple-select deselection API.


89. Interview Question: What is the difference between selectByVisibleText and selectByValue?

Answer: selectByVisibleText() selects an option according to the text displayed to the user, whereas selectByValue() selects an option according to its HTML value attribute.


90. Interview Question: Which dropdown selection method should you use?

Answer: The appropriate method depends on the application. Use visible text when the displayed label is the stable identifier, value when the HTML value is stable and suitable, and index only when index-based selection is intentional and reliable.


91. Interview Question: What happens if the element passed to Select is not a select tag?

Answer: Selenium's Select constructor checks the element's tag name. If it is not a SELECT element, an UnexpectedTagNameException can be thrown.


92. Important Methods Summary

MethodPurpose
selectByVisibleText()Select option by displayed text
selectByValue()Select option by value attribute
selectByIndex()Select option by index
getOptions()Get all options
getFirstSelectedOption()Get first/current selected option
getAllSelectedOptions()Get all selected options
isMultiple()Check multiple-selection support
deselectByVisibleText()Deselect by visible text
deselectByValue()Deselect by value
deselectByIndex()Deselect by index
deselectAll()Deselect all options in a multi-select


93. Quick Revision

1. Inspect the dropdown.

2. Check whether it is a <select> element.

3. Locate the dropdown.

4. Create a Select object.

5. Select using:

   - selectByVisibleText()

   - selectByValue()

   - selectByIndex()

6. Verify the selected option.

7. For multiple select:

   - select multiple options

   - use deselect methods

8. For dynamic dropdowns:

   - use explicit waits

9. For custom dropdowns:

   - do not use Select class

10. Keep dropdown logic reusable.


94. Final Conclusion

Select Dropdown handling is an essential Selenium WebDriver skill because dropdown controls appear in registration forms, search forms, checkout pages, profile pages, administration panels, filters, and many other web applications.

For a standard HTML <select> element, Selenium's Select class provides a convenient API for selecting options by visible text, value, or index, retrieving available and selected options, and working with multiple-select controls.

The most important concept is to first inspect the HTML. If the control is a genuine <select> element, use the Select class. If the application uses a custom dropdown built with divs, buttons, list items, or JavaScript overlays, interact with the actual elements instead.

For reliable automation, use stable locators, select options using meaningful identifiers, wait for dynamically populated options, verify the selected value, and keep reusable dropdown logic inside utility or Page Object classes.


95. Course Resources

To learn Selenium WebDriver, dropdown handling, locators, waits, browser automation, Page Object Model, TestNG, framework development, and practical automation testing, explore the following resources:

whatsapp